import { EventKey } from "../common/Key";
import { GameState } from "./GameState";
import { ComposeSpace } from "./GameDefine";
import { GameData } from "./GameData";
import { EnergyMgr } from "../../resources/components/energy/EnergyMgr";
import { TaskMgr } from "./TaskMgr";
var SceneGame = cc.Class({
    extends: require('BaseScene'),
    GameMgr: null,

    statics: {
        instance: null,
    },

    properties: {
        pfbItemAnimal: cc.Prefab,
        pfbItemCoin: cc.Prefab,
        pfbItemPoop: cc.Prefab,
        pfbItemEffectMerge: cc.Prefab,
        pfbItemRandomAnimal: cc.Prefab,

        nodAnimalParent: cc.Node,
        nodPoopParent: cc.Node,
        nodEffectParent: cc.Node,
        nodRandomAnimalParent: cc.Node,

        labCoin: cc.Label,
        labProductionSpeed: cc.Label,

        labNextAnimalPrice: cc.Label,
    },

    onLoad() {
        this._super();
        SceneGame.instance = this;
        this._initNodePool();
        this._time1 = 0;
    },

    start() {
        TaskMgr.addDaliyTask(0,1);
        G.game.gameAudioMgr.playBgm();

        G.partner.sendEvent('场景', { '类型': 'game' });

        this._updateCoinLabel();
        this._updateNextAnimalPriceLabel();

        this._checkOutline();

        if (!GameData.getGuided()) {
            this._startGuide();
        } else {
            // 本地存储的动物数据
            let data = GameData.readAliveAnimal();
            for (let i = 0; i < data.length; i++) {
                this._genAnimal(data[i].index);
            }
        }

        this.schedule(() => {
            this._addRandomAnimal();
        }, 120)
    },

    // 新手指导
    _startGuide() {
        this._genAnimal(0, cc.v2(60, 60), false);
        this._genAnimal(0, cc.v2(60, -60), false);
        this._genAnimal(0, cc.v2(-60, 60), false);
        this._genAnimal(0, cc.v2(-60, -60), false);
        G.ui.openUI('PanelGuide');
    },

    onEnable() {
        this._super();
        this._registEvent();
    },

    onDisable() {
        this._super();
        this._unRegistEvent();
    },
    // 初始化节点池
    _initNodePool() {
        G.utils.createPool('nodePoolAnimal', this.pfbItemAnimal, 1);
        G.utils.createPool('nodePoolCoin', this.pfbItemCoin, 1);
        G.utils.createPool('nodePoolPoop', this.pfbItemPoop, 1);
        G.utils.createPool('nodePoolEffectMerge', this.pfbItemEffectMerge, 1);
        G.utils.createPool('nodePoolRandomAnimal', this.pfbItemRandomAnimal, 1);
    },

    // 添加随机动物
    _addRandomAnimal() {
        let animalIndex = GameState.getMaxIndexCanBuyByCoin();
        let node = G.utils.getPoolNode('nodePoolRandomAnimal');
        node.parent = this.nodRandomAnimalParent;
        node.getComponent('ItemRandomAnimal').init(G.utils.random(0, animalIndex));
    },

    // 刷新动物节点的层级
    _updateAnimalZIndex() {
        this.nodAnimalParent.children.sort((a, b) => {
            return b.y - a.y;
        })
    },

    // 尝试合成动物
    _tryComposeAnimal(animal) {
        let arr = this.nodAnimalParent.children;
        let index = animal.getIndex();
        let minSpace = ComposeSpace;
        let otherComp;
        for (let i = 0; i < arr.length; i++) {
            let tComp = arr[i].getComponent('ItemAnimal');
            if (tComp.getIndex() != index) {
                continue;
            }
            if (tComp == animal) {
                continue;
            }
            let space = G.utils.getDistance(arr[i].position, animal.node.position)
            if (space < minSpace) {
                minSpace = space;
                otherComp = tComp;
            }
        }
        if (!otherComp) {
            return;
        }

        this._genAnimal(index + 1, otherComp.node.position);
        this._showEffectMerge(otherComp.node.position);

        GameData.removeAliveAnimal(otherComp);
        GameData.removeAliveAnimal(animal);
        otherComp.recycle();
        animal.recycle();

        this._updateCurrAnimalIndex(index + 1);
        this._updateNextAnimalPriceLabel();
        G.game.gameAudioMgr.playMerge();
        TaskMgr.addDaliyTask(3,1);
    },

    _updateCurrAnimalIndex(index) {
        let currIndex = GameData.getCurrAnimalIndex();
        if (index > currIndex) {
            GameData.setCurrAnimalIndex(index);
            G.ui.openUI('PanelUnlockAnimal', { index: index });
        }
    },

    _genAnimal(index, pos, canJump) {
        let node = G.utils.getPoolNode('nodePoolAnimal');
        node.parent = this.nodAnimalParent;
        if (!pos) {
            pos = cc.v2(G.utils.random(-this.nodAnimalParent.width / 2, this.nodAnimalParent.width / 2),
                G.utils.random(-this.nodAnimalParent.height / 2, this.nodAnimalParent.height / 2));
        }
        node.position = pos;
        node.getComponent('ItemAnimal').init(index, canJump);
        GameData.addAliveAnimal(node.getComponent('ItemAnimal'));
    },

    _tryBuyAnimal() {
        let maxCount = GameData.getMaxAnimalCount();
        let aliveAnimalData = GameData.getAliveAnimalData();
        if (aliveAnimalData.length >= maxCount) {
            G.game.toast('场上动物数量已达上限', 1);
            return;
        }

        let animalIndex = GameState.getMaxIndexCanBuyByCoin();

        let currCoin = GameData.getCurrCoin();
        let price = GameState.getAnimalCoinPrice(animalIndex);

        if (G.bignumber.compose(currCoin, price) == -1) {
            // G.game.toast('金币不足', 1);
            G.ui.openUI('PanelAddCoin');
            return;
        }
        GameData.subCoin(price);
        GameData.addAnimalBuyCount(animalIndex);
        this._genAnimal(animalIndex);
        this._updateNextAnimalPriceLabel();
        TaskMgr.addDaliyTask(1,1);
    },

    _showEffectMerge(pos) {
        let node = G.utils.getPoolNode('nodePoolEffectMerge');
        node.parent = this.nodEffectParent;
        node.position = pos;
    },

    // 更新钻石
    _updateDiamondLabel() {

    },
    // 更新金币
    _updateCoinLabel() {
        let coin = GameData.getCurrCoin();
        this.labCoin.string = G.bignumber.toUnitType(coin);
    },

    // 更新金币生产速度
    _updateProductionSpeedLabel() {
        let speed = GameState.getProductionSpeed();
        this.labProductionSpeed.string = G.bignumber.toUnitType(speed) + '/S';
    },

    // 更新购买按钮上的价格
    _updateNextAnimalPriceLabel() {
        let animalIndex = GameState.getMaxIndexCanBuyByCoin();
        let price = GameState.getAnimalCoinPrice(animalIndex);
        this.labNextAnimalPrice.string = 'LV.' + (animalIndex + 1) + '  ' + G.bignumber.toUnitType(price);
    },

    // 更新购买按钮状态，金币变化的时候，动物变化的时候
    _updateBuyBtnState() {

    },

    // 检测离线时间，onshow事件触发，所以后台也算作离线
    _checkOutline() {
        let date = GameData.getOutLineTime();
        let time = Math.floor((Date.now() - date) / 1000);
        // 小于60s不算离线
        if (time < 60) {
            return;
        }

        let speed = GameState.getProductionSpeed();
        let coin = G.bignumber.plus(speed, time);
        G.ui.openUI('PanelOutline', { time: time, coin: coin });
        GameData.resetOutLineTime();
    },

    buttonListener(button) {
        G.game.gameAudioMgr.playBtn();
        let name = button.node.name;
        if (name == "btnBuyAnimal") {
            this._tryBuyAnimal();
        } else if (name == "btnSetting") {
            G.ui.openUI('PanelSetting');
        } else if (name == "btnTurntable") {
            G.ui.openUI('PanelTurntable');
        } else if (name == "btnRecruit") {
            G.ui.openUI('PanelRecruit');
        } else if (name == "btnRank") {
            G.ui.openUI('PanelRank');
        } else if (name == "btnTask") {
            G.ui.openUI('PanelTask');
        } else if (name == "btnSign") {
            G.ui.openUI('PanelSign');
        } else if (name == "btnEnergy") {
            if (GameData.getCanGetShareEnergy()) {
                G.partner.sendEvent('分享', { '类型': '能量' });
                G.partner.share({ title: '萌萌宠物带回家？' }, () => {
                    EnergyMgr.addEnergys(5);
                    G.game.toast('能量+' + 5, 1);
                    GameData.addToadyShareEnergyCount();
                    TaskMgr.addDaliyTask(5,1);
                });
            } else {
                G.game.toast('今日免费能量次数已达上限', 1);
            }

        }
    },
    _onFire(eventName, param) {
        if (eventName == EventKey.EVENT_SCORE_CHANGE) {
            this.labScore.string = GameState.getScore() + '';
        } else if (eventName == EventKey.EVENT_UPDATE_ANIMAL_ZINDEX) {
            // this._updateAnimalZIndex();
        } else if (eventName == EventKey.EVENT_TRY_COMPOSE_ANIMAL) {
            this._tryComposeAnimal(param.animal);
        } else if (eventName == EventKey.EVENT_UPDATE_COIN) {
            this._updateCoinLabel();
            this._updateBuyBtnState();
        } else if (eventName == EventKey.EVENT_UPDATE_PRODUCTION_SPEED) {
            this._updateProductionSpeedLabel();
        } else if (eventName == EventKey.EVENT_UPDATE_NEXT_ANIMAL_PRICE) {
            this._updateNextAnimalPriceLabel();
            this._updateBuyBtnState();
        } else if (eventName == EventKey.EVENT_GEN_ANIMAL) {
            this._genAnimal(param.index);
        } else if (eventName == EventKey.EVENT_ON_SHOW) {
            this._checkOutline();
        }
    },

    _registEvent() {
        G.onFire.on(EventKey.EVENT_SCORE_CHANGE, this._onFire, this);
        G.onFire.on(EventKey.EVENT_UPDATE_ANIMAL_ZINDEX, this._onFire, this);
        G.onFire.on(EventKey.EVENT_TRY_COMPOSE_ANIMAL, this._onFire, this);
        G.onFire.on(EventKey.EVENT_UPDATE_COIN, this._onFire, this);
        G.onFire.on(EventKey.EVENT_UPDATE_PRODUCTION_SPEED, this._onFire, this);
        G.onFire.on(EventKey.EVENT_UPDATE_NEXT_ANIMAL_PRICE, this._onFire, this);
        G.onFire.on(EventKey.EVENT_GEN_ANIMAL, this._onFire, this);
        G.onFire.on(EventKey.EVENT_ON_SHOW, this._onFire, this);
    },
    _unRegistEvent() {
        G.onFire.off(EventKey.EVENT_SCORE_CHANGE, this._onFire, this);
        G.onFire.off(EventKey.EVENT_UPDATE_ANIMAL_ZINDEX, this._onFire, this);
        G.onFire.off(EventKey.EVENT_TRY_COMPOSE_ANIMAL, this._onFire, this);
        G.onFire.off(EventKey.EVENT_UPDATE_COIN, this._onFire, this);
        G.onFire.off(EventKey.EVENT_UPDATE_PRODUCTION_SPEED, this._onFire, this);
        G.onFire.off(EventKey.EVENT_UPDATE_NEXT_ANIMAL_PRICE, this._onFire, this);
        G.onFire.off(EventKey.EVENT_GEN_ANIMAL, this._onFire, this);
        G.onFire.off(EventKey.EVENT_ON_SHOW, this._onFire, this);
    },

    update(dt) {
        this._time1 += dt;
        if (this._time1 >= 0.2) {
            this._time1 = 0;
            this._updateAnimalZIndex();
        }
    },
});

